package com.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.web.servlet.utils.Utils;

public class GetFaceServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String userId =request.getParameter("userId");
		
		String faceData =request.getParameter("faceData");
		
		
		String FILE_SAVE_PATH=request.getSession().getServletContext().getRealPath("/")+"headImage/";
		
		System.out.println("FILE_SAVE_PATH===="+FILE_SAVE_PATH);
		
		writeFile(FILE_SAVE_PATH,userId+".png",faceData);
		
		out.flush();
		out.close();
	}
	
	private void writeFile(String path,String fileName,String strData)
	{
		try
        {
	        String pathFileName=path+fileName;
	        File filePath=new File(path);
	        File file =new File(pathFileName);
	        if (!filePath.isDirectory())
	        {
	        	filePath.mkdirs();
	        }
	        if(!file.exists())
	        {
	        	file.createNewFile();
	        }
	        
	        filePath=null;
	            
//	        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        FileOutputStream out=new FileOutputStream(file,false); //如果追加方式用true        
//	        StringBuffer sb=new StringBuffer();
//	        sb.append("-----------"+sdf.format(new Date())+"------------\n");
//	        sb.append(str+"\n");
	        //因为上传的数据为十六进制字符串，需要转换一下
	        out.write(Utils.toStringHex(strData));
	        //out.write(strData.toString().getBytes("utf-8"));//注意需要转换对应的字符集
	        out.close();
        }
        catch(IOException ex)
        {
        	ex.printStackTrace();
            System.out.println("writeFile IOException="+ex.getStackTrace());
        }
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
